import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useSelector } from 'react-redux'
import to from 'await-to-js'
import _ from 'lodash'

import { toZero } from '@/utils/common'
import { RootState, useAppDispatch } from '@/store'
import { signAction, updataSignData } from '@/store/modules/signStore'
import { useDateTimer } from '@/hooks/dataTimeHook'
import { ResponseSignsTime } from '@/api/sign/type'
import { applyAction, updataApplyData } from '@/store/modules/applyStore'
import { ResponseApplyList } from '@/api/apply/type'


const useException = () => {
    const dispatch = useAppDispatch()

    const userInfo = useSelector((state: RootState) => state.userStore.infos)
    const signData = useSelector((state: RootState) => state.signStore.signData)
    const applyList = useSelector((state: RootState) => state.applyStore.applyList)

    const [ searchParams, setSearchParams ] = useSearchParams()

    const { dateYear, dateMonth } = useDateTimer()

    const [ punchInfo, setPunchInfo ] = useState<[ string, string ][]>([])

    const [ month, setMonth ] = useState(searchParams.get('month') || dateMonth)

    const monthOptions: { value: number, label: string }[] = []
    for (let i = 1; i <= 12; i += 1) {
        monthOptions.push({
            value: i,
            label: `${i}月`
        })
    }

    //  用户点击select 切换月份 回掉函数
    const handleCalendarSelect = (val: string | number) => {
        setMonth(val)
        setSearchParams({ month: val.toString() })
    }

    //  获取打卡数据
    useEffect(() => {
        const getSignData = async () => {
            const { payload } = await dispatch(signAction(userInfo._id))
            const { errcode, infos } = payload as ResponseSignsTime
            if (errcode !== 0) return false
            dispatch(updataSignData(infos))
        }
        if (_.isEmpty(signData)) {
            getSignData()
        }

    }, [ signData, userInfo._id ])


    useEffect(() => {
        const getApplyData = async () => {
            const { payload } = await dispatch(applyAction({ applicantid: userInfo._id }))
            const { errcode, rets } = payload as ResponseApplyList
            if (errcode !== 0) return false
            dispatch(updataApplyData(rets))
        }

        if (_.isEmpty(applyList)) {
            getApplyData()
        }
    }, [ applyList ])

    let currentMonthData
    if (signData.detail) {
        const rest = signData.detail[toZero(month)] as { [index: string]: unknown }
        currentMonthData = (Object.entries(rest) as [ string, string ][]).filter(item => item[1] !== '正常出勤').sort()
    }

    const applyListMonth = applyList.filter(item => {
        const startTime = (item.time as string[])[0].split(' ')[0].split('-')
        const endTime = (item.time as string[])[1].split(' ')[0].split('-')
        return startTime[1] <= toZero(month) && endTime[1] >= toZero(month)
    })

    const renderTime = (date: string) => {
        const ret = ((signData.time as { [index: string]: unknown })[toZero(month)] as {
            [index: string]: unknown
        })[date]
        if (Array.isArray(ret)) {
            return ret.join('-')
        } else {
            return '暂无打卡记录'
        }
    }

    return { dateYear, month, monthOptions, currentMonthData, renderTime, handleCalendarSelect, applyListMonth }
}

export default useException
